package br.senai.web.filter;

import java.io.IOException;

import javax.persistence.EntityManager;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;

import br.senai.util.PersistenceManagerFactory;

@WebFilter(filterName="EntityManagerFilter",urlPatterns="/*")
public class EntityManagerFilter implements Filter {

	public void init(FilterConfig filterConfig) throws ServletException {

	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {

		try {

			EntityManager entityManager = PersistenceManagerFactory.currentEntityManager();
			request.setAttribute("entityManager", entityManager);

			filterChain.doFilter(request, response);

			if (entityManager != null && entityManager.isOpen())
				entityManager.close();
			else {
				entityManager = (EntityManager) request.getAttribute("entityManager");

				if (entityManager != null && entityManager.isOpen())
					entityManager.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void destroy() {

	}

}